package com.example.tests;

import java.util.concurrent.TimeUnit;

import org.junit.*;
import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;

import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.example.pages.InternalPage;
import com.example.pages.LoginPage;
import com.example.pages.ManagementPage;

import ru.esteru.selenium.factory.WebDriverFactory;

public class createNewUserTest {
  private WebDriver driver;
  private WebDriverWait wait;
  private String baseUrl;
  private StringBuffer verificationErrors = new StringBuffer();
private LoginPage loginPage;
private InternalPage somePage;
private InternalPage internalPage;
private ManagementPage managementPage;

  @Before
  public void setUp() throws Exception {
    driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    wait = new WebDriverWait(driver, 10);
    baseUrl = "http://localhost/";

  }

  @Test
  public void createNewUser() {
		goToMainPage();
	    loginAs("admin", "admin");
	    gotoUserManagementConsole();
	    createUser("user2", "user2@mail.com", "password");
	    logout();  
  }
  
   
	private void createUser(String username, String email, String password) {
		managementPage.userNameField.clear();
		managementPage.userNameField.sendKeys(username);
		managementPage.emailField.clear();
		managementPage.emailField.sendKeys(email);
		managementPage.passwordField.clear();
		managementPage.passwordField.sendKeys(password);
		managementPage.password2Field.clear();
		managementPage.password2Field.sendKeys(password);
		managementPage.saveButton.click();

	}

	private void gotoUserManagementConsole() {
		internalPage.menuUserManagementLink.click();
	}

	private void logout() {
		somePage.menuLogoutLink.click();
		wait.until(alertIsPresent()).accept();
	}
	
	private void loginAs(String username, String password) {
		loginPage.userNameField.clear();
		loginPage.userNameField.sendKeys(username);
		loginPage.passwordField.clear();
		loginPage.passwordField.sendKeys(password);
		loginPage.loginButton.click();
		
	}
	
	
	private void goToMainPage() {
		driver.get(baseUrl + "/php4dvd/");
		loginPage = PageFactory.initElements(driver, LoginPage.class);
		somePage = PageFactory.initElements(driver, InternalPage.class);
		internalPage = PageFactory.initElements(driver, InternalPage.class);
		managementPage = PageFactory.initElements(driver, ManagementPage.class);
		
	}
  @After
  	public void tearDown() throws Exception {
	    String verificationErrorString = verificationErrors.toString();
	    if (!"".equals(verificationErrorString)) {
	      fail(verificationErrorString);
    }
  }

 }
